package com.findmeastore.bc.impl;

import java.sql.Timestamp;
import java.util.List;

import com.findmeastore.bc.IUserBc;
import com.findmeastore.bo.UserBo;
import com.findmeastore.bo.UserCredentialsBo;
import com.findmeastore.dao.IUserDAO;
import com.findmeastore.dto.UserDto;

public class UserBcImpl implements IUserBc{

	private IUserDAO userDao;
	
	public boolean isValidUser(String userName, String password){
		return userDao.findIfUserPresent(userName, password);
	}
	
	public List<UserBo> getAllUsers(){
		return userDao.getAllUsers();
	}
	
	public UserBo getUserById(Integer id){
		return userDao.getUserById(id);
	}
	
	public void saveUser(UserDto dto){
		Integer id = dto.getId();
		UserBo userBo = null;
		UserCredentialsBo userCredentialsBo = null;
		if(id!=null&&id>0){//update
			userBo = userDao.getUserById(id);
			userCredentialsBo = userDao.getUserCredentialsByUserId(id);
		}else {//save
			userBo = new UserBo();
			userCredentialsBo = new UserCredentialsBo();
			userBo.setCreationTstamp(new Timestamp(System.currentTimeMillis()));
			userCredentialsBo.setCreationTstamp(new Timestamp(System.currentTimeMillis()));
			userBo.setCreatedByUserId(dto.getModifiedById());
			userCredentialsBo.setCreatedByUserId(dto.getModifiedById());
		}
		userBo.setUserName(dto.getUsername());
		userBo.setLastModifiedTstamp(new Timestamp(System.currentTimeMillis()));
		userBo.setLastModifiedByUserId(dto.getModifiedById());
		userBo.setEmail(dto.getEmail());
		userBo.setMobile(dto.getMobile());
		userCredentialsBo.setPassword(dto.getPassword());
		userCredentialsBo.setLastModifiedTstamp(new Timestamp(System.currentTimeMillis()));
		userCredentialsBo.setLastModifiedByUserId(dto.getModifiedById());

		userDao.saveUser(userBo);
		userCredentialsBo.setUserId(userBo.getId());
		userDao.saveUserCredentials(userCredentialsBo);
	}

	public IUserDAO getUserDao() {
		return userDao;
	}

	public void setUserDao(IUserDAO userDao) {
		this.userDao = userDao;
	}
}
